package cn.dengta.webapp.trade.config;

import java.math.BigDecimal;
import java.time.LocalTime;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;

import cn.dengta.common.redis.RedisUtil;
import cn.dengta.common.util.Common;
import cn.dengta.common.util.SpringUtil;
import cn.dengta.webapp.user.cache.UserCaches;
import cn.dengta.webapp.user.model.UserSketch;
import com.alibaba.fastjson2.JSONPath;
import com.alibaba.fastjson2.JSONReader;
import lombok.*;
import me.codeplayer.util.NumberUtil;
import me.codeplayer.util.StringUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 推广员定制规则配置
 */
@Component
@Getter
@Setter
@ConfigurationProperties(prefix = "agent.custom")
public class CustomAgentConfig implements InitializingBean {

	/** redis key */
	public static final String recRechargeUserKey = "rec:rechargeUser";

	/** 定制需求的推广员ID */
	Set<Long> agentIds;
	/** 定制需求推广员旗下用户的视频价格：钻石/分钟 */
	Integer videoPrice = 100;
	/** 最小充值金额 */
	BigDecimal minRecharge = BigDecimal.valueOf(50);
	/** 审核人员 */
	Long verifyUserId = 102L;

	/** 定制规则每天在几点开始生效 */
	int startHour = 0;
	/** 定制规则每天在几点结束生效（不包括该小时） */
	int endHour = 8;

	@Setter(AccessLevel.NONE)
	transient String agentIdsStr;

	public CustomAgentConfig() {
		setAgentIds("777");
	}

	public void setAgentIds(String agentIdStrs) {
		final List<Long> agentIds = Common.split(agentIdStrs, ',', Long::valueOf, true);
		//noinspection ConstantConditions
		this.agentIds = Set.copyOf(agentIds);
		this.agentIdsStr = agentIdStrs;
	}

	@Resource
	transient UserCaches userCaches;

	static CustomAgentConfig instance;

	/** 只是当前时间定制规则是否已启用 */
	public boolean ruleEnabled() {
		LocalTime now = LocalTime.now();
		final int hour = now.getHour();
		if (startHour < endHour) { // 00 ~ 08
			return startHour <= hour && hour < endHour;
		} else { // 15 ~ 03 跨天
			return startHour <= hour || hour < endHour;
		}
	}

	public boolean includeUser(UserSketch user) {
		final Long agentId = user.getAgentId();
		return agentId != null && agentIds.contains(agentId);
	}

	public static CustomAgentConfig get() {
		if (instance == null) {
			instance = SpringUtil.getBean(CustomAgentConfig.class);
		}
		return instance;
	}

	static final JSONPath agentIdPath = JSONPath.compile("$.atId");

	public boolean includeUser(Long userId) {
		final String json = RedisUtil.getStringRedisTemplate().<String, String>opsForHash().get(UserCaches.REDIS_KEY, userId.toString());
		if (StringUtil.isEmpty(json)) {
			return includeUser(userCaches.get(userId, false));
		}
		JSONReader jsonReader = JSONReader.of(json);
		final Long agentId = NumberUtil.getLong(agentIdPath.extract(jsonReader), null);
		return agentId != null && agentIds.contains(agentId);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		instance = this;
	}

}
